import React, { useState, useEffect } from 'react';
import {
  IonCard,
  IonCardHeader,
  IonCardTitle,
  IonCardSubtitle,
  IonCardContent,
  IonItem,
  IonLabel,
  IonSelect,
  IonSelectOption,
  IonInput,
  IonButton,
  IonIcon,
  IonToast,
  IonList,
  IonListHeader,
  IonNote,
  IonToolbar,
} from '@ionic/react';
import {
  folderOpenOutline,
  checkmarkCircleOutline,
  linkOutline,
  searchOutline,
} from 'ionicons/icons';
import { useTranslation } from 'react-i18next';
import { terminalService } from '../../services/TerminalService';

type OperatingSystem = 'darwin' | 'linux' | 'windows';

interface OSConfig {
  name: string;
  defaultPath: string;
  configFile: string;
}

const OS_CONFIGS: Record<OperatingSystem, OSConfig> = {
  darwin: {
    name: 'macOS',
    defaultPath: '~/.ollama/models',
    configFile: '~/.zshrc or ~/.bash_profile',
  },
  linux: {
    name: 'Linux',
    defaultPath: '/usr/share/ollama/.ollama/models',
    configFile: '~/.bashrc or ~/.profile',
  },
  windows: {
    name: 'Windows',
    defaultPath: 'C:\\Users\\%username%\\.ollama\\models',
    configFile: 'System Environment Variables',
  },
};

const ModelLocationSettings: React.FC = () => {
  const { t } = useTranslation();
  const [selectedOS, setSelectedOS] = useState<OperatingSystem>('darwin');
  const [customPath, setCustomPath] = useState('');
  const [currentPath, setCurrentPath] = useState('');
  const [showToast, setShowToast] = useState(false);
  const [toastMessage, setToastMessage] = useState('');
  const [toastType, setToastType] = useState<'success' | 'error'>('success');
  const [isVerifying, setIsVerifying] = useState(false);

  useEffect(() => {
    detectOS();
    getCurrentPath();
  }, []);

  const detectOS = async () => {
    try {
      const result = await terminalService.executeCommand('uname');
      if (result.output.toLowerCase().includes('darwin')) {
        setSelectedOS('darwin');
      } else if (result.output.toLowerCase().includes('linux')) {
        setSelectedOS('linux');
      } else {
        setSelectedOS('windows');
      }
    } catch {
      // Default to darwin if detection fails
      setSelectedOS('darwin');
    }
  };

  const getCurrentPath = async () => {
    try {
      const result = await terminalService.executeCommand('echo $OLLAMA_MODELS');
      setCurrentPath(result.output.trim() || OS_CONFIGS[selectedOS].defaultPath);
    } catch (error) {
      console.error('Failed to get current path:', error);
    }
  };

  const handleSave = async () => {
    if (!customPath) return;

    try {
      let command: string;
      if (selectedOS === 'windows') {
        command = `setx OLLAMA_MODELS "${customPath}"`;
      } else {
        command = `echo 'export OLLAMA_MODELS="${customPath}"' >> ${
          selectedOS === 'darwin' ? '~/.zshrc' : '~/.bashrc'
        }`;
      }

      const result = await terminalService.executeCommand(command);
      if (result.exitCode === 0) {
        setToastType('success');
        setToastMessage(t('settings.modelLocation.success'));
        setCurrentPath(customPath);
        setCustomPath('');
      } else {
        setToastType('error');
        setToastMessage(t('settings.modelLocation.errors.changeFailed'));
      }
    } catch (error) {
      setToastType('error');
      setToastMessage(t('settings.modelLocation.errors.changeFailed'));
    }
    setShowToast(true);
  };

  const handleVerify = async () => {
    setIsVerifying(true);
    try {
      const result = await terminalService.executeCommand('ollama show --modelfile');
      setToastType('success');
      setToastMessage(result.output);
    } catch (error) {
      setToastType('error');
      setToastMessage(t('settings.modelLocation.errors.verificationFailed'));
    }
    setShowToast(true);
    setIsVerifying(false);
  };

  const handleDirectorySelect = async () => {
    try {
      const selectedPath = await window.electron.selectDirectory();
      if (selectedPath) {
        setCustomPath(selectedPath);
      }
    } catch (error) {
      console.error('Failed to select directory:', error);
      setToastType('error');
      setToastMessage(t('settings.modelLocation.errors.dirSelectFailed'));
      setShowToast(true);
    }
  };

  return (
    <IonCard>
      <IonCardHeader>
        <IonCardTitle>{t('settings.modelLocation.title')}</IonCardTitle>
        <IonCardSubtitle>{t('settings.modelLocation.subtitle')}</IonCardSubtitle>
      </IonCardHeader>

      <IonCardContent>
        <div className="space-y-6">
          {/* Description */}
          <div className="bg-base-200 p-4 rounded-lg">
            <p className="text-sm">{t('settings.modelLocation.description')}</p>
          </div>

          {/* Current Location */}
          <div>
            <IonListHeader>
              <h3 className="text-lg font-semibold">{t('settings.modelLocation.current')}</h3>
            </IonListHeader>
            <IonItem lines="none" className="bg-base-200 rounded-lg">
              <IonIcon icon={folderOpenOutline} slot="start" />
              <IonLabel className="font-mono text-sm">{currentPath}</IonLabel>
            </IonItem>
          </div>

          {/* OS Selection */}
          <div>
            <IonListHeader>
              <h3 className="text-lg font-semibold">{t('settings.modelLocation.osSelection')}</h3>
            </IonListHeader>
            <IonItem>
              <IonSelect
                value={selectedOS}
                onIonChange={e => setSelectedOS(e.detail.value)}
                interface="popover"
                aria-label={t('settings.modelLocation.selectOS')}
              >
                {Object.entries(OS_CONFIGS).map(([key, config]) => (
                  <IonSelectOption key={key} value={key}>
                    {config.name}
                  </IonSelectOption>
                ))}
              </IonSelect>
            </IonItem>
          </div>

          {/* Custom Path Input */}
          <div>
            <IonListHeader>
              <h3 className="text-lg font-semibold">{t('settings.modelLocation.customPath')}</h3>
            </IonListHeader>
            <IonItem>
              <IonInput
                aria-label={t('settings.modelLocation.enterPath')}
                labelPlacement="stacked"
                value={customPath}
                onIonChange={e => setCustomPath(e.detail.value!)}
                placeholder={OS_CONFIGS[selectedOS].defaultPath}
                className="font-mono"
              />
              <IonButton
                fill="clear"
                slot="end"
                onClick={handleDirectorySelect}
                title={t('settings.modelLocation.selectDirectory')}
              >
                <IonIcon icon={searchOutline} slot="icon-only" />
              </IonButton>
            </IonItem>
          </div>

          {/* OS-specific Instructions */}
          <div className="bg-base-200 p-4 rounded-lg">
            <h4 className="font-semibold mb-2">{t('settings.modelLocation.instructions')}</h4>
            <p className="text-sm mb-2">
              {t(`settings.modelLocation.${selectedOS}.instructions`)}
            </p>
            <code className="block bg-base-300 p-2 rounded text-sm">
              {selectedOS === 'windows'
                ? t('settings.modelLocation.windows.command')
                : `export OLLAMA_MODELS="${customPath || OS_CONFIGS[selectedOS].defaultPath}"`}
            </code>
            <IonNote className="block mt-2">
              {t('settings.modelLocation.configNote', { file: OS_CONFIGS[selectedOS].configFile })}
            </IonNote>
          </div>

          {/* Action Buttons */}
          <IonToolbar>
            <div className="flex justify-between">
              <IonButton
                fill="outline"
                onClick={handleVerify}
                disabled={isVerifying}
              >
                <IonIcon slot="start" icon={checkmarkCircleOutline} />
                {t('settings.modelLocation.verify')}
              </IonButton>
              <div className="space-x-2">
                <IonButton
                  fill="outline"
                  color="medium"
                  onClick={() => setCustomPath('')}
                >
                  {t('common.cancel')}
                </IonButton>
                <IonButton
                  onClick={handleSave}
                  disabled={!customPath}
                >
                  {t('common.save')}
                </IonButton>
              </div>
            </div>
          </IonToolbar>

          {/* Help Links */}
          <div className="mt-4">
            <IonListHeader>
              <h3 className="text-lg font-semibold">{t('common.help')}</h3>
            </IonListHeader>
            <IonList className="bg-base-200 rounded-lg">
              <IonItem href="https://github.com/ollama/ollama/main/docs/modelfile.md" target="_blank">
                <IonIcon slot="start" icon={linkOutline} />
                <IonLabel>{t('settings.modelLocation.help.docs')}</IonLabel>
              </IonItem>
              <IonItem href="https://github.com/ollama/ollama/main/docs/faq.md" target="_blank" lines="none">
                <IonIcon slot="start" icon={linkOutline} />
                <IonLabel>{t('settings.modelLocation.help.faq')}</IonLabel>
              </IonItem>
            </IonList>
          </div>
        </div>
      </IonCardContent>

      <IonToast
        isOpen={showToast}
        onDidDismiss={() => setShowToast(false)}
        message={toastMessage}
        duration={3000}
        color={toastType === 'success' ? 'success' : 'danger'}
      />
    </IonCard>
  );
};

export default ModelLocationSettings; 